package srx.open.com.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.nostra13.universalimageloader.core.ImageLoader;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.listener.CountListener;
import de.greenrobot.event.EventBus;
import srx.open.com.R;
import srx.open.com.activity.BaseActivity;
import srx.open.com.activity.LoginActivity;
import srx.open.com.activity.MyCourseActivity;
import srx.open.com.activity.SettingsActivity;
import srx.open.com.bean.CoursePublish;
import srx.open.com.bean.CourseSubscribe;
import srx.open.com.bean.Logout;
import srx.open.com.bean.User;
import srx.open.com.utils.CommonUtils;
import srx.open.com.utils.Constants;
import srx.open.com.utils.UserUtils;
import srx.open.com.widgets.ActionSheet;
import srx.open.com.widgets.ActionSheet.ActionSheetListener;
import srx.open.com.widgets.CircleImageView;

/*
 * 我的fragment模块.
 * 
 * @author hailongqiu 356752238@qq.com
 *
 */

public class MineFragment extends BaseFragment {

    private static final String TAG = "MineFragment";

    public static MineFragment newInstance(String s) {
        MineFragment mineFragment = new MineFragment();
        return mineFragment;
    }

    // 标题栏
    @Bind(R.id.back_iv)
    ImageView back_iv;
    @Bind(R.id.right_lay)
    View right_lay;
    @Bind(R.id.right_tv)
    TextView right_tv;

    // 用户信息
    @Bind(R.id.user_name)
    TextView user_name; // 用户名(不是账号).
    @Bind(R.id.active_iv)
    CircleImageView active_iv; // 头像

    // 我的课程，订阅，已完成的订阅
    @Bind(R.id.my_pub_course_num_tv)
    TextView my_pub_course_num_tv;
    @Bind(R.id.my_sub_course_num_tv)
    TextView my_sub_course_num_tv;
    @Bind(R.id.my_over_sub_course_num_tv)
    TextView my_over_sub_course_num_tv;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_mine, container, false);
        ButterKnife.bind(this, view);
        initAllViews();
        return view;
    }

    @Override
    public void initAllDatas() {
    }

    public void initAllViews() {
        initAllEventBus();
        initWidgets();
        initUserInfo();
    }

    /**
     * 初始化控件属性.
     */
    private void initWidgets() {
        initTitls();
    }

    /**
     *  初始化标题栏.
     */
    private void initTitls() {
        back_iv.setVisibility(View.INVISIBLE);
        right_lay.setVisibility(View.INVISIBLE);
    }

    /**
     * 初始化用户信息.
     */
    private void initUserInfo() {
        User user = UserUtils.getCurrentUser(mContext);
        onEvent(user);
    }

    private void initAllEventBus() {
        EventBus.getDefault().register(this); // 注册事件.
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this); // 注销事件.
    }

    public void onEvent(Logout logout) {
        User user = UserUtils.getCurrentUser(mContext);
        onEvent(user);
    }

    /**
     * 接收更新的信号.
     */
    public void onEvent(User user) {
        if (user != null) { // 登录更新.
             /* 更新用户名称(不是用户账号) */
            String name = user.getNick();
            if (TextUtils.isEmpty(name)) // 如果用户没有设置用户名，则显示当前的账号号码(account).
                name = user.getUsername();
            user_name.setText(name);
            /* 更新用户头像 */
            String avatarUrl = user.getAvatar();
            ImageLoader.getInstance().displayImage(avatarUrl, active_iv,
                    CommonUtils.getOptions(R.drawable.ic_launcher));
            /* 更新我的课程数量 */
            setMyPubCourseNumUpdate(user);
            /* 更新我的订阅课程数量 */
            setMySubCourseNumUpdate(user);
            /* 更新我已经完成订阅的课程的数量 */
            setOverMySubCourseNumUpdate(user);
        } else { // 退出登录.更新.
            user_name.setText("未登录");
            active_iv.setImageResource(R.drawable.ic_launcher);
            my_pub_course_num_tv.setText("");
            my_sub_course_num_tv.setText("");
            my_over_sub_course_num_tv.setText("");
        }
    }

    /**
     * 设置我的课程数量.
     */
    private void setMyPubCourseNumUpdate(User user) {
        BmobQuery<CoursePublish> coursePublishQuery = new BmobQuery<CoursePublish>();
        // 统计自己的课程数目.
        if (user != null) {
            coursePublishQuery.addWhereEqualTo("username", user.getUsername());
        }
        coursePublishQuery.count(mContext, CoursePublish.class, new CountListener() {
            @Override
            public void onSuccess(int count) {
                int myPubCourseNum = count;
                my_pub_course_num_tv.setText("" + myPubCourseNum);
                Log.d(TAG, "[我的课程]coursePublishQuery.count onSuccess count:" + count);
            }

            @Override
            public void onFailure(int code, String msg) {
                my_pub_course_num_tv.setText("" + 0);
                Log.d(TAG, "[我的课程]coursePublishQuery.count onFailure code:" + code + " msg:" + msg);
            }
        });
    }

    /**
     * 设置我订阅的课程的数量.
     */
    private void setMySubCourseNumUpdate(User user) {
        BmobQuery<CourseSubscribe> courseSubscribeQuery = new BmobQuery<CourseSubscribe>();
        // 统计自己的订阅数目.
        if (user != null) {
            courseSubscribeQuery.addWhereEqualTo("username", user.getUsername());
        }
        courseSubscribeQuery.count(mContext, CourseSubscribe.class, new CountListener() {
            @Override
            public void onSuccess(int count) {
                int mySubCourseNum = count;
                my_sub_course_num_tv.setText("" + mySubCourseNum);
                Log.d(TAG, "[订阅课程]courseSubscribeQuery.count onSuccess count:" + count);
            }

            @Override
            public void onFailure(int code, String msg) {
                my_sub_course_num_tv.setText("" + 0);
                Log.d(TAG, "[订阅课程]courseSubscribeQuery.count onFailure code:" + code + " msg:" + msg);
            }
        });
    }

    /**
     * 设置已经完成的课程订阅的数量.
     */
    private void setOverMySubCourseNumUpdate(User user) {
        my_over_sub_course_num_tv.setText("" + 0);
    }

    /*
   * 设置界面.
   */
    @OnClick(R.id.settings_lay)
    void startSettingsActivity(View view) {
        Intent intents = new Intent(mContext, SettingsActivity.class);
        startActivity(intents);
    }

    @OnClick(R.id.active_iv)
    void onActiveImageView(View view) {
        if (!checkLogin())
            return;
        // 修改用户头像.
        ((BaseActivity) getActivity()).iv_set_avator = active_iv; // 保存用户头像.
        getActivity().setTheme(R.style.ActionSheetStyleIOS7);
        ActionSheet
                .createBuilder(getActivity(),
                        getActivity().getSupportFragmentManager())
                .setCancelButtonTitle("取消")
                .setOtherButtonTitles("本地相册", "照相")
                .setCancelableOnTouchOutside(true)
                .setListener(new ActionSheetListener() {
                    @Override
                    public void onOtherButtonClick(ActionSheet actionSheet,
                                                   int index) {
                        switch (index) {
                            case Constants.LOCAL_PIC_CODE: // 本地相册.
                                ((BaseActivity) getActivity()).callLocalActionPick();
                                break;
                            case Constants.PHOTO_CODE: // 照相.
                                ((BaseActivity) getActivity()).callImageCapture();
                                break;
                        }
                    }

                    @Override
                    public void onDismiss(ActionSheet actionSheet,
                                          boolean isCancel) {
                    }
                }).show();
    }

    @OnClick(R.id.info_lay)
    void info_lay(View view) {
        if (!checkLogin())
            return;
        // 修改用户资料.[跳转到用户资料修改界面]
    }

    /*
     * 我的课程界面.
     */
    @OnClick(R.id.my_pub_course_rlay)
    void startMyCoursePubActivity(View view) {
        if (!checkLogin())
            return;
        openActivity(MyCourseActivity.class);
    }

    /*
     * 我的课程订阅界面.
     */
    @OnClick(R.id.my_sub_course_rlay)
    void startMyCourseSubActivity(View view) {
        if (!checkLogin())
            return;
//		openActivity(CourseSubActivity.class);
    }

    /*
     * 我已完成订阅的界面.
     */
    @OnClick(R.id.my_over_sub_course_rlay)
    void startMyOverSubCourseRlay(View view) {
        if (!checkLogin())
            return;
        //		openActivity(CourseSubActivity.class);
    }

    /**
     * 检查是否已经登录了.
     */
    private boolean checkLogin() {
        User user = UserUtils.getCurrentUser(mContext);
        if (user == null) {
            Intent intents = new Intent(mContext, LoginActivity.class);
            startActivity(intents);
            return false;
        }
        return true;
    }

}
